﻿using DynamicExpresso;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using SmartMotion.Core.Mgrs;

namespace SmartMotion.Core.Tools
{
    public class ActionExpression : ActionItem
    {
        public Lambda Lambda;
        public List<Parameter> Parameters;

        public List<VarInfo> Vars { get; set; }

        public string BoolExpression { get; set; }

        public bool BoolResult { get; set; }    
        public ActionExpression()
        {
            Parameters = new List<Parameter>();
            Vars = new List<VarInfo>();
        }

        //解析lambda
        public override UIForm GetConfigForm()
        {
            return new FrmExpression(this);
        }

        public override bool Initilize()
        {
            Stopwatch sw = Stopwatch.StartNew();

            try
            {
                var target = new Interpreter();
                Parameters.Clear();
                for (var index = 0; index < ParaTypes.Count; index++)
                {
                    var paraType = ParaTypes[index];
                    Parameters.Add(new Parameter(ParaNames[index],Type.GetType(paraType)));
                }

                Lambda = target.Parse(BoolExpression, Parameters.ToArray());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Em.GetEvent<DebugMessage>().Publish($"编译{ItemName}失败\r{e.Message}");
            }

            Em.GetEvent<DebugMessage>().Publish($"编译{ItemName}成功 耗时{sw.ElapsedMilliseconds}");
            return true;
        }

        //执行lambda
        protected override ActionResult RunMethod()
        {
            if (Lambda == null)
            {
                Initilize();
            }   
            //执行
            BoolResult = false;
            try
            {
                //List<object> args = new List<object>();
                //foreach (var varInfo in Vars)
                //{
                //    VarInfo varInfo1 = VarMgr.Ins.GetVarByName(varInfo.Name);
                //    args.Add(varInfo1.Value);
                //}
                //result = (bool)Lambda.Invoke(args.ToArray());

                BoolResult = (bool)Lambda.Invoke(
                    Vars.Select(varInfo => VarMgr.Ins.GetVarByName(varInfo.Name))
                        .Select(varInfo1 => varInfo1.Value).Cast<object>().ToArray());

                Em.GetEvent<DebugMessage>().Publish($"运行表达式{BoolExpression}={BoolResult}");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Em.GetEvent<DebugMessage>().Publish($"运行表达式{BoolExpression}失败\r {e.Message}");
                return ActionResult.Error;
            }

            return ActionResult.Success;
        }

        public override UIPage GetParasPage()
        {
            return null;
        }
    }
}
